//
//  KYTabbarController.m
//  SwiftHealing
//
//  Created by chenchen on 16/8/18.
//  Copyright © 2016年 ios0610. All rights reserved.
//

#import "KYNavigationController.h"
#import "KYTabbarController.h"
#import "HMMineTableViewController.h"


@interface KYTabbarController ()
@property (weak, nonatomic) UITapGestureRecognizer *tap;
@end

@implementation KYTabbarController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    
    // MARK: - 1.添加拖拽
    [self setupPanGesture];
    
//    [self.tabBar setTintColor:[UIColor colorWithRed:78/255.0 green:207/255.0 blue:204/255.0 alpha:1]];
    [self.tabBar setTintColor:[UIColor colorWithRed:245 / 255.0 green:69 / 255.0 blue:74 / 255.0 alpha:1]];
    self.tabBar.backgroundColor = [UIColor whiteColor];
    
    [self addChildViewControllers];
    
    // 注册通知中心
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addChildViewControllers) name:@"tabBarController" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(upData) name:@"QQBtnLogin" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(upData) name:@"microblogLogin" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(upData) name:@"weiChatLogin" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(registerUp) name:@"registerUp" object:nil];
}

/**
 *  刷新tabbar的子控制器
 */
- (void)upData {
    
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"loginState"]
        ) {
        
//        [CCKYTools sharedTools].isLogin = true;
        [self addChildViewControllers];
    }
}
//
- (void)registerUp {
    
   
        
//        [CCKYTools sharedTools].isLogin = true;
    
        [self addChildViewControllers];
  
}

/**
 *  加载子控制器
 */
- (void)addChildViewControllers
{

//    NSString *mineClassName = [CCKYTools sharedTools].isLogin ? @"CCKYLoginSuccessController" : @"KYLogInController";
    
    //初始化一个数组,这个数组里面存的是字典,每个字典有3个键值对,分别对应"类名","标题","图片"
    NSArray* array = @[
        @{
            @"className" : @"HMHomeViewController",
            @"title" : @"首页",
            @"imageName" : @"首页.png",
            @"imageName_selected" : @"首页-点击.png"
        },
        @{
            @"className" : @"YKDoclistController",
            @"title" : @"名医通",
            @"imageName" : @"名医通.png",
            @"imageName_selected" : @"名医通点击.png"
        },
        @{
            @"className" : @"HMPublicActityController",
            @"title" : @"药品",
            @"imageName" : @"公益活动.png",
            @"imageName_selected" : @"公益点击.png"
        },
        @{
            @"className" : @"HMMineTableViewController",
            @"title" : @"我的",
            @"imageName" : @"我的.png",
            @"imageName_selected" : @"我的点击.png"
        }
    ];

    //初始化临时数组保存创建的子控制器
    NSMutableArray* arrayM = [NSMutableArray array];
    //遍历数组加载子控制器
    for (NSDictionary* dict in array) {
        //创建子控制器
        UIViewController* vc = [self loadChildViewControllerWithDict:dict];
        //添加到可变数组中
        [arrayM addObject:vc];
    }
    //返回可变数组的copy对象
    self.viewControllers = arrayM.copy;
}

#pragma mark - 创建子控制器的方法
/**
 *  加载子控制器
 *
 *  @param className 类名
 *  @param title     标题
 *  @param imageName 图片
 *
 *  @return 返回控制器
 */
- (UIViewController*)loadChildViewControllerWithDict:(NSDictionary*)dict
{
    
    if ([dict[@"className"] isEqualToString:@"HMMineTableViewController"]) {
        UIStoryboard *sb = [UIStoryboard storyboardWithName:@"HMMineTableViewController" bundle:nil];
        
        HMMineTableViewController *mineVc = [sb instantiateInitialViewController];
        
        // 3.设置标题 这样设置相当于同时把tabbar的title和navbar的title都设置了
        mineVc.title = dict[@"title"];
        // [vc.tabBarController.tabBar setTintColor:[UIColor redColor]];
        
        // 4.设置选中和不选中的图片
        //不是选中的图片
        mineVc.tabBarItem.image = [UIImage
                               imageNamed:dict[@"imageName"]];
        
        //选中的图片
        mineVc.tabBarItem.selectedImage =
        [UIImage imageNamed:dict[@"imageName_selected"]];
        // 5.嵌套导航控制器
        KYNavigationController* nav =
        [[KYNavigationController alloc] initWithRootViewController:mineVc];
        
        // 6.返回导航控制器
        return nav;

    }

    // 1.通过类名字符串获取类对象
    Class clz = NSClassFromString(dict[@"className"]);
    

    // 2.通过类对象创建控制器
    UIViewController* vc = [[clz alloc] init];

    // 3.设置标题 这样设置相当于同时把tabbar的title和navbar的title都设置了
    vc.title = dict[@"title"];
    // [vc.tabBarController.tabBar setTintColor:[UIColor redColor]];

    // 4.设置选中和不选中的图片
    //不是选中的图片
    vc.tabBarItem.image = [UIImage
        imageNamed:dict[@"imageName"]];

    //选中的图片
    vc.tabBarItem.selectedImage =
        [UIImage imageNamed:dict[@"imageName_selected"]];
    // 5.嵌套导航控制器
    KYNavigationController* nav =
        [[KYNavigationController alloc] initWithRootViewController:vc];

    // 6.返回导航控制器
    return nav;
}

#pragma mark - 侧滑控制器相关方法
//- (BOOL)navigationShouldPopOnBackButton
//{
//    [[AppDelegate globalDelegate] toggleLeftDrawer:self animated:YES];
//    NSLog(@"NO");
//    return NO;
//}
#pragma mark - 监听方法
// 拖拽的方法
- (void)panAction:(UIPanGestureRecognizer *)recognizer {
    
    // 如果导航控制器当前有多个子控制器!就别动了!
    if (self.selectedViewController.childViewControllers.count > 1) {
        return;
    }
    
    // 1.获取偏移量
    CGPoint translate = [recognizer translationInView:recognizer.view];
    
    // 2.重置
    [recognizer setTranslation:CGPointZero inView:recognizer.view];
    
    // 3.开始处理
    switch (recognizer.state) {
        case UIGestureRecognizerStateBegan:
        case UIGestureRecognizerStateChanged:
            
            // 如果向左,不要动!
            if (translate.x + recognizer.view.frame.origin.x < 0) {
                return;
            }
            // 让视图移动
            recognizer.view.transform = CGAffineTransformTranslate(recognizer.view.transform, translate.x, 0);
            
            break;
            
        case UIGestureRecognizerStateEnded:
        {
            // 判断, -> 如果够远!
            CGFloat destW = 64;
            CGFloat screenW = recognizer.view.bounds.size.width;
            
            // 当前停留位置的x,是否大于了屏幕的一半
            if (recognizer.view.frame.origin.x > screenW * 0.5) {
                
                [UIView animateWithDuration:0.25 animations:^{
                    
                    recognizer.view.transform = CGAffineTransformMakeTranslation(screenW - destW, 0);
                } completion:^(BOOL finished) {
                    
                    [self setupTapGesture];
                }];
                //#warning - 不能忘了break!
                break;
            }
            
            [self removeTapGesture];
        }
            
            
        case UIGestureRecognizerStateCancelled:
        case UIGestureRecognizerStateFailed:
        {
            // 恢复
            [UIView animateWithDuration:0.25 animations:^{
                
                recognizer.view.transform = CGAffineTransformIdentity;
                
            }];
        }
            break;
            
        default:
            break;
    }
    
}
- (void)setupPanGesture {
    
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panAction:)];
    
    [self.view addGestureRecognizer:pan];
    
}
#pragma mark - 添加子控制器的代码
- (void)setupChildVcs {
    
    UINavigationController *messageNav = [self navWithClassName:@"HMHomeController" andTitle:@"首页" image:nil];
    
    UINavigationController *contactNav = [self navWithClassName:@"HMDocoterViewController" andTitle:@"医生" image:nil];
    
    self.viewControllers = @[messageNav, contactNav];
    
}
#pragma mark -- 添加点按手势
- (void)setupTapGesture {
    //  如果添加了点击手势  就返回
    if(_tap != nil)
    {
        return;
        
    }
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
    [self.view addGestureRecognizer:tap];
    _tap = tap;
    
    
}
//实现点按方法
- (void)tapAction:(UITapGestureRecognizer *)recognizer
{
    if(CGAffineTransformIsIdentity(self.view.transform))
    {
        return;
    }
    //点击以后 让视图恢复形变
    [UIView animateWithDuration:0.25 animations:^{
        self.view.transform = CGAffineTransformIdentity;
    } completion:^(BOOL finished) {
        //   恢复形变以后，需要移除点按
        [self removeTapGesture];
    }];
    
    
    
    
}
- (void)removeTapGesture
{
    [self.view removeGestureRecognizer:_tap];
    
    
}

- (UINavigationController *)navWithClassName:(NSString *)clsName andTitle:(NSString *)title image:(UIImage *)img {
    
    // 1.转为类
    Class cls = NSClassFromString(clsName);
    // 2.创建对象
    UIViewController *vc = [[cls alloc] init];
    
    // 2.2　增加断言
    // condition 条件
    // desc 错误时的描述！ -> 写字符串！
    // isKindOfClass 判断某个对象是否为某个类型或者其子类类型的对象！
    // isMemberOfClass -> 必须是该类型的对象才满足条件！
    NSAssert([vc isKindOfClass:[UIViewController class]], @"%@ 写错了, 没有这个类", clsName);
    
    // 3.直接设置title -> 会将tabBarItem.title NavigationItem.title 同时设置！
    vc.title = title;
    //    vc.tabBarItem.image = img;
    
    // 4.包装成导航控制器
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
    
    // 5.返回
    return nav;
}



@end
